<?php
namespace Common\Model;
use Think\Model;

class ArticleModel extends Model{
	
	protected $tableName = 'article';

	//自动完成

	protected $_auto = array(
		array('sendtime','addtime',3,'function'),
		array('attr','_arrt',3,'function'),

	);

	public function _attr($value){
		if($value){
			$data=implode(',',$value);
			return $data;
		}

	}

	public  function addtime(){
		return time();
	}


	//添加数据
	public function add_data(){
		//需要添加三张表
		//文章表
		$data=$_POST;
		$data['sendtime']=time();
		$data['attr']=implode(',',$_POST['attr']);
		$id=$this->add($data);

		//文章数据表
		$neirong=array(
			'keywords'=>$_POST['keywords'],
			'content' =>$_POST['editorValue'],
			'description'=>$_POST['description'],
			'article_aid'=>$id,

		);
		D('ArticleData')->add_data($neirong);

		//标签表
		foreach(I('post.tid',array()) as $v){
			$data=array(
				'article_aid'=>$id,
				'tag_tid'=>$v,
				'category_cid'=>$_POST['category_cid'],
			);
			D('ArticleTag')->add($data);
		}
		
	}
	//获取数据
	public function get_data($where=NULL){
		if($where==NULL){
			$data=$this->order('sendtime asc')->select();
			return $data;
		}else{
			$data=$this->where($where)->find();
			return $data;
		}

	}

	//删除
	public function del_data($where=NULL){
		$this->where($where)->delete();
	}

	//修改
	public function save_data(){
		$aid=$_POST['aid'];
		$data=$_POST;
		$where=array('aid'=>$aid);
		$data['editime']=time();
		$data['attr']=implode(',',$_POST['attr']);
		//修改文章表
		$this->where($where)->save($data);

		//修改文章数据表
		D(ArticleData)->save_data(array('article_aid'=>$aid),$data);

		//修改标签表
		D('ArticleTag')->del_data(array('article_aid'=>$aid));
		foreach(I('post.tid',array()) as $v){
			$data=array(
				'article_aid'=>$aid,
				'tag_tid'=>$v,
				'category_cid'=>$_POST['category_cid'],
			);
			D('ArticleTag')->add($data);
		}
	}
}
